package com.yuyou.fn.tms.controller;

import com.yuyou.fn.common.lang.Tuple2;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Created by lzh on 2019/1/30.
 */
public class Binder {
    private static class SmartCustomDateEditor extends PropertyEditorSupport {

        private final static List<Tuple2<Pattern,String>> suppertPatterns = Arrays.asList(
                Tuple2.of(Pattern.compile("\\d{4}-\\d{2}-\\d{2}") , "yyyy-MM-dd"),
                Tuple2.of(Pattern.compile("\\d{4}-\\d{2}-\\d{2}\\s\\d{2}") , "yyyy-MM-dd HH"),
                Tuple2.of(Pattern.compile("\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}") , "yyyy-MM-dd HH:mm"),
                Tuple2.of(Pattern.compile("\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}") , "yyyy-MM-dd HH:mm:ss")
        );


        private SimpleDateFormat simpleDateFormat ;


        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            if(!StringUtils.hasText(text)) {
                this.setValue((Object)null);
            }else {
                for(Tuple2<Pattern,String> patternStringTuple : suppertPatterns ){

                    if(patternStringTuple.getFirst().matcher(text).matches()){
                        simpleDateFormat = new SimpleDateFormat(patternStringTuple.getSecond());
                        simpleDateFormat.setLenient(false);
                        break;
                    }
                }
                if( simpleDateFormat == null ){
                    throw new IllegalArgumentException("Could not parse date: " + text );
                }

                try {
                    this.setValue(this.simpleDateFormat.parse(text));
                } catch (ParseException var3) {
                    throw new IllegalArgumentException("Could not parse date: " + var3.getMessage(), var3);
                }
            }




        }

        @Override
        public String getAsText() {
            Date value = (Date)this.getValue();
            return value != null ? this.simpleDateFormat.format(value) : "";
        }
    }


    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
        binder.registerCustomEditor(Date.class, new SmartCustomDateEditor() );
    }
}
